using System.IO;
using UnityEditor;
using UnityEditor.Animations;
using UnityEngine;

namespace IQIGame.Onigao.GamePlay.Editors
{
    public class GenAnimatorLive2D : GenAnimatorLevelEntity
    {
        public override ArtModeGenType genAnimatorType => ArtModeGenType.Live2D;
        
        protected override string entityGenConfigPath => $"Assets/EditorConfig/ArtToolConfig/EntityGen/Live2D/{entityName}.asset";
        protected override string defaultGenConfigPath => "Assets/EditorConfig/ArtToolConfig/EntityGen/Common/Entity_Live2D.asset";

        public override void GenAnimatorController()
        {
            if (string.IsNullOrEmpty(this.entityName))
            {
                return;
            }

            //// create animator controller
            CreateController();
            //// add controller parameters
            AddParameters();
            //// Create Anim States
            CreateAnimStates();

            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
        }

        public override string GetAnimatorResPath()
        {
            var animatorResPath = Path.Combine(basePath, $"{entityName}.controller");
            return animatorResPath;
        }
        
        public override AnimationClip GetAnimationClipAndSetLoop(string clipName, bool isLoop)
        {
            var clipPath = Path.Combine(basePath, this.genAnimatorConfig.AniamtionPath, $"{entityName}@{clipName}.anim").Replace("\\", "/");
            return AssetDatabase.LoadAssetAtPath<AnimationClip>(clipPath);
        }

        public override AnimatorState CreateBaseIdleState(AnimatorStateMachine layerMachine, bool isDefault, Vector3 pos)
        {
            AnimatorState stateStand = null;
            var idleClip = this.GetAnimationClipAndSetLoop(this.genAnimatorConfig.Name_Idle, true);
            if (idleClip != null)
            {

                stateStand = layerMachine.AddState(AnimatorToolConstant.State_Idle, pos);
                stateStand.motion = idleClip;
            }
            else
            {
                stateStand = layerMachine.AddState(AnimatorToolConstant.State_Empty, pos);
            }
            if (isDefault)
            {
                layerMachine.defaultState = stateStand;
            }
            return stateStand;
        }
    }
}
